package io.github.topcatv.mall.model.sys.controller;

import io.github.topcatv.mall.common.ao.ReturnObject;
import io.github.topcatv.mall.common.support.JsonArg;
import io.github.topcatv.mall.model.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author liuyi
 */
@Api(tags = "AuthApi")
@RestController
public class AuthController {

    @Resource
    private IUserService userService;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, defaultValue = ""),
            @ApiImplicitParam(name = "password", value = "密码", required = true, defaultValue = ""),
            @ApiImplicitParam(name = "mobile", value = "用户手机号", required = true, defaultValue = "")
    })
    @PostMapping(value = "${jwt.route.register}")
    public ReturnObject registry(@JsonArg String username,
                                 @JsonArg String password,
                                 @JsonArg String mobile) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ReturnObject.error("用户名或密码不能为空");
        }
        Integer userId = userService.registryUser(username, password, mobile);
        return ReturnObject.success().put("id", userId);
    }

    @ApiOperation(value = "token刷新", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "旧token", required = true, defaultValue = "")
    })
    @PostMapping(value = "${jwt.route.refresh}")
    public ReturnObject refresh(@RequestHeader("${jwt.header}") String token) {
        return ReturnObject.success().put("token", userService.refreshToken(token.substring(tokenHead.length() + 1)));
    }

}